// src/main/database.js
const Database = require('better-sqlite3');

class DatabaseManager {
  constructor(dbPath, authManager) {
    this.dbPath = dbPath;
    this.authManager = authManager;
    this.db = null;
    this.connected = false;
  }

  // 通过会话ID连接数据库
  async connectWithSession(sessionId) {
    try {
      if (this.connected && this.db) {
        return true;
      }

      // 通过会话ID获取数据库密钥
      const dbKey = await this.authManager.getDbKeyBySession(sessionId);
      
      const options = {};
      if (dbKey) {
        options.key = dbKey;
      }
      
      this.db = new Database(this.dbPath, options);
      this.db.pragma('journal_mode = WAL');
      this.db.pragma('foreign_keys = ON');
      this.connected = true;
      
      console.log('数据库连接成功（使用会话）');
      return true;
    } catch (error) {
      console.error('数据库连接失败:', error);
      throw error;
    }
  }

  // 所有数据库操作都需要会话ID
  async query(sessionId, sql, params = []) {
    await this.connectWithSession(sessionId);
    
    try {
      const stmt = this.db.prepare(sql);
      return stmt.all(...params);
    } catch (error) {
      console.error('查询失败:', error);
      throw error;
    }
  }

  async insert(sessionId, sql, params = []) {
    await this.connectWithSession(sessionId);
    
    try {
      const stmt = this.db.prepare(sql);
      const result = stmt.run(...params);
      return result.lastInsertRowid;
    } catch (error) {
      console.error('插入失败:', error);
      throw error;
    }
  }

  async update(sessionId, sql, params = []) {
    await this.connectWithSession(sessionId);
    
    try {
      const stmt = this.db.prepare(sql);
      const result = stmt.run(...params);
      return result.changes;
    } catch (error) {
      console.error('更新失败:', error);
      throw error;
    }
  }

  async delete(sessionId, sql, params = []) {
    await this.connectWithSession(sessionId);
    
    try {
      const stmt = this.db.prepare(sql);
      const result = stmt.run(...params);
      return result.changes;
    } catch (error) {
      console.error('删除失败:', error);
      throw error;
    }
  }

  // 断开连接
  disconnect() {
    if (this.db) {
      this.db.close();
      this.db = null;
      this.connected = false;
      console.log('数据库连接已关闭');
    }
  }
}

module.exports = DatabaseManager;